<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="测试类型" prop="testTypeId">
        <el-select v-model="queryParams.testTypeId" placeholder="请选择测试类型" clearable>
          <el-option
            v-for="item in testTypeOptions"
            :key="item.testTypeId"
            :label="item.typeName"
            :value="item.testTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" prop="questionText">
        <el-input
          v-model="queryParams.questionText"
          placeholder="请输入题目内容"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维度" prop="dimension">
        <el-select v-model="queryParams.dimension" placeholder="请选择维度" clearable>
          <el-option label="外向性(E)" value="E" />
          <el-option label="内向性(I)" value="I" />
          <el-option label="感觉(S)" value="S" />
          <el-option label="直觉(N)" value="N" />
          <el-option label="思考(T)" value="T" />
          <el-option label="情感(F)" value="F" />
          <el-option label="判断(J)" value="J" />
          <el-option label="知觉(P)" value="P" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['mbti:question:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mbti:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mbti:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['mbti:question:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="题目ID" align="center" prop="questionId" width="80" />
      <el-table-column label="测试类型" align="center" prop="testTypeName" width="120" />
      <el-table-column label="题目内容" align="left" prop="questionText" :show-overflow-tooltip="true" />
      <el-table-column label="题目顺序" align="center" prop="questionOrder" width="80" />
      <el-table-column label="维度" align="center" prop="dimension" width="80">
        <template #default="scope">
          <el-tag :type="getDimensionTagType(scope.row.dimension)">{{ getDimensionName(scope.row.dimension) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['mbti:question:edit']">修改</el-button>
          <el-button link type="primary" icon="View" @click="handleOptions(scope.row)">选项</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['mbti:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改MBTI题目对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="测试类型" prop="testTypeId">
          <el-select v-model="form.testTypeId" placeholder="请选择测试类型">
            <el-option
              v-for="item in testTypeOptions"
              :key="item.testTypeId"
              :label="item.typeName"
              :value="item.testTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="questionText">
          <el-input v-model="form.questionText" type="textarea" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="题目顺序" prop="questionOrder">
          <el-input-number v-model="form.questionOrder" :min="1" :max="200" />
        </el-form-item>
        <el-form-item label="维度" prop="dimension">
          <el-select v-model="form.dimension" placeholder="请选择维度">
            <el-option label="外向性(E)" value="E" />
            <el-option label="内向性(I)" value="I" />
            <el-option label="感觉(S)" value="S" />
            <el-option label="直觉(N)" value="N" />
            <el-option label="思考(T)" value="T" />
            <el-option label="情感(F)" value="F" />
            <el-option label="判断(J)" value="J" />
            <el-option label="知觉(P)" value="P" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/mbti/question";
import { listTestType } from "@/api/mbti/testType";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');

const questionList = ref([]);
const testTypeOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    testTypeId: null,
    questionText: null,
    dimension: null
  },
  rules: {
    testTypeId: [
      { required: true, message: "测试类型不能为空", trigger: "change" }
    ],
    questionText: [
      { required: true, message: "题目内容不能为空", trigger: "blur" }
    ],
    questionOrder: [
      { required: true, message: "题目顺序不能为空", trigger: "blur" }
    ],
    dimension: [
      { required: true, message: "维度不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询MBTI题目列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取测试类型选项 */
function getTestTypeOptions() {
  listTestType().then(response => {
    testTypeOptions.value = response.rows;
  });
}

/** 获取维度名称 */
function getDimensionName(dimension) {
  const dimensionMap = {
    'E': '外向性',
    'I': '内向性',
    'S': '感觉',
    'N': '直觉',
    'T': '思考',
    'F': '情感',
    'J': '判断',
    'P': '知觉'
  };
  return dimensionMap[dimension] || dimension;
}

/** 获取维度标签类型 */
function getDimensionTagType(dimension) {
  const typeMap = {
    'E': 'success',
    'I': 'info',
    'S': 'warning',
    'N': 'danger',
    'T': 'primary',
    'F': 'success',
    'J': 'warning',
    'P': 'info'
  };
  return typeMap[dimension] || '';
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    questionId: null,
    testTypeId: null,
    questionText: null,
    questionOrder: null,
    dimension: null,
    status: "0"
  };
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.questionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加MBTI题目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _questionId = row.questionId || ids.value
  getQuestion(_questionId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改MBTI题目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      if (form.value.questionId != null) {
        updateQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _questionIds = row.questionId || ids.value;
  proxy.$modal.confirm('是否确认删除MBTI题目编号为"' + _questionIds + '"的数据项？').then(function() {
    return delQuestion(_questionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 选项管理 */
function handleOptions(row) {
  proxy.$router.push({
    path: '/mbti/option',
    query: { questionId: row.questionId, questionText: row.questionText }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mbti/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getTestTypeOptions();
});
</script>
